import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from 'axios'

// 配置axios默认值 - 服务器环境使用相对路径
axios.defaults.baseURL = ''  // 使用相对路径，让Nginx代理处理
axios.defaults.headers.common['Content-Type'] = 'application/json'

console.log('API Base URL:', axios.defaults.baseURL || '相对路径')

// 从localStorage获取token
const token = localStorage.getItem('token')
if (token) {
  // 确保token格式正确
  axios.defaults.headers.common['Authorization'] = token.startsWith('Bearer ') ? token : `Bearer ${token}`
}

// 添加请求拦截器，处理请求
axios.interceptors.request.use(
  config => {
    console.log('发送请求:', config.url)
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 添加axios响应拦截器处理错误
axios.interceptors.response.use(
  response => response,
  error => {
    console.error('请求错误:', error)
    if (error.response && error.response.status === 401) {
      console.log('认证失败，但不自动跳转，允许游客访问')
      // 不自动跳转，让游客也能看到界面
      // 只在用户主动操作时才跳转登录页
    }
    return Promise.reject(error)
  }
)

const app = createApp(App)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(createPinia())
app.use(router)
app.use(ElementPlus)

app.mount('#app')

// 关闭页面/刷新/关闭标签时自动清除登录信息
window.addEventListener('beforeunload', () => {
  localStorage.removeItem('token');
  localStorage.removeItem('userInfo');
});